<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>debunce throttle</title>
    <style>
        #content {
            width: 300px;
            height: 300px;
            background: #f40;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    
    <button id="btn">click and debunce</button>

    <input type="text" id="ipt">

    <div id="content">

    </div>
    <script>

        let btn = document.getElementById('btn');
        let ipt = document.getElementById('ipt');
        let content = document.getElementById('content');

        function fn () {
            console.log('debunce');
        }

        /* function debunce (fn,timeout) {
            let timer = null;

            return function () {
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn();
                }, timeout);
            }
        }

        btn.onclick = debunce(fn,1500);

        function throttle (fn,timeout,interval) {
            let previous = null;
            let timer = null;

            return function () {
                let now = new Date();
                if (!previous) previous = now;
                if (now - previous > interval) {
                    clearTimeout(timer);
                    fn();
                    previous = now;
                } else {
                    clearTimeout(timer);
                    timer = setTimeout(()=>{
                        fn();
                    },timeout)
                }
            }

        }

        function gn () {
            console.log('1');
        }

        content.onmousemove = throttle(gn,500,500); */

        function throttle (fn,interval,timeout) {
            let timer = null;
            let prev = null;
            return function () {
                let current = new Date();
                if(!prev) prev = current;
                if(current-prev>interval){
                    clearTimeout(timer);
                    fn();
                    prev = current;
                } else {
                    clearTimeout(timer);
                    timer = setTimeout(() => {
                        fn()
                    }, timeout);
                }
            }
        }

        content.onmousemove = throttle(fn,500,500);




        
    
    </script>
</body>
</html>